from django.shortcuts import render,reverse,get_object_or_404
from .models import Collection,FileList      #导入项目表
from .util import saveFile,getpid         #导入工具
from django.contrib.auth.models import User
from django.http import FileResponse    #文件下载
from django.conf import settings
from django.contrib import auth
import os, zipfile, re



#用户主页
def userpage(requests):
    user = requests.user
    context ={"projects":Collection.objects.filter(user=user),}
    return render(requests,'collection/userpage.html',context)



# 新建文件收集表页面
def setFileName(request):
    context = {'ppid':getpid()}
    return render(request,'collection/setfilename.html',context)


# 新建文件表单 上传页面
def upload(request):
    referer = request.META.get('HTTP_REFERER', reverse('index'))
    ppid = request.GET['ppid']
    userid = request.GET['user']
    user = User.objects.get(username=userid)
    context = {}
    if request.method == 'POST':                                #提交表单
        projectname = request.POST['projectname']
        collection = Collection.objects.filter(projectname=projectname,user=user)
        if collection.exists():
            return render(request, 'collection/information.html', {"info": "该文件柜已存在,请重新创建或查看!", "referer": referer})
        else:
            #保存表
            project = Collection()
            project.projectname = projectname
            project.username = request.POST['username']
            project.date = request.POST['date']
            project.otherinfo = request.POST['otherinfo']
            project.word1 = request.POST['word1']
            project.word2 = request.POST['word2']
            project.word3 = request.POST['word3']
            project.word4 = request.POST['word4']
            project.ppid = ppid
            project.user = user
            project.save()
    else:                                                   #提交文件
        project = Collection.objects.get(ppid=ppid,user=user)

    context['collection'] = project
    return render(request, 'collection/upload.html', context)






# 上传文件
def info(request):
    referer = request.META.get('HTTP_REFERER', reverse('index'))
    ppid = request.GET['ppid']
    userid = request.GET['user']
    user = User.objects.get(username=userid)
    collection = get_object_or_404(Collection, ppid=ppid, user=user)
    if request.method == "POST":
        try:
            f1 = request.FILES['myfile']
        except:
            return render(request, 'collection/information.html', {'info': "未选择文件!", "referer": referer})

        try:
            filename = f1.name.split("-")
            username = filename[0]
            obj = FileList.objects.filter(username=username,ppid=ppid)
            if obj.exists():
                obj.delete()        #删除已存在的
        except:
            return render(request, 'collection/information.html', {'info': "文件格式错误!", "referer": referer})

        try:                         # 新建
            file = FileList()
            file.username = username
            file.word1 = filename[1]
            file.word2 = filename[2]
            file.filename = f1.name
            file.projectname = collection
            file.filesize = f1.size
            file.ppid = ppid
            file.file = f1
            file.save()
        except:
            return render(request, 'collection/information.html', {'info': "提交失败!", "referer": referer})

        return render(request, 'collection/information.html', {'info': "文件上传成功！", "referer": referer})





#统计汇总
def count(request):
    context = {}
    user = request.user
    ppid = request.GET['ppid']
    files = FileList.objects.filter(ppid=ppid)
    project = Collection.objects.get(ppid=ppid)
    context['files'] = files
    context['num'] = files.count()
    context['project'] = project
    return render(request,'collection/count.html',context)



#文件打包下载
def downloadfile(request):
    ppid = request.GET['ppid']
    projectname = ppid + '.zip'
    dir = os.path.join(settings.MEDIA_ROOT,ppid)
    tmp = os.path.join(settings.MEDIA_ROOT,'tmp',projectname)
    make_zip(dir,tmp)
    file=open(tmp,'rb')
    response =FileResponse(file)
    response['Content-Type']='application/octet-stream'
    response['Content-Disposition']='attachment;filename="{}"'.format(projectname)
    return response


#打包目录为zip文件（压缩）
def make_zip(source_dir, output_filename):
  zipf = zipfile.ZipFile(output_filename, 'w',zipfile.ZIP_DEFLATED)
  pre_len = len(os.path.dirname(source_dir))
  for parent, dirnames, filenames in os.walk(source_dir):
    for filename in filenames:
      pathfile = os.path.join(parent, filename)
      arcname = pathfile[pre_len:].strip(os.path.sep)   #相对路径
      zipf.write(pathfile, arcname)
  zipf.close()








